<script setup>
import {nextTick, onMounted, ref, watch} from "vue";
import {
  closeToast,
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showNotify,
  showSuccessToast,
  showToast
} from "vant";
import request from "@/assets/js/mobileRequest";
import qs from "qs";
import {currentUser} from "@/App.vue";

const loading = ref(true)
const pullDisable = ref(false)
const cardList = ref([])
const list = ref([]);
const activeTab = ref('event');
var coordtransform = require('coordtransform')
const acceptDialog = ref({
  show: false
})
const start = ref(1)
const pageSize = 10;

const orderListInfo = ref({
  start: 1,
  pageSize: 10
})
const pullLoading = () => {
  start.value = parseInt(Math.random()*20);
  let a = {
    start: start.value,
    pageSize: pageSize
  };
  let data = qs.stringify(a);
  request({
    method: "post",
    url: BASE_URL + '/v1/card/selectLimit',
    data: data
  }).then(res => {
    if (res.data.code === 2000) {
      console.log(res.data.data)
      cardList.value = res.data.data;
      list.value = res.data.data;
      loading.value = false
      isLoading.value = false;
      finishLoad.value = false;
      start.value += pageSize;
    }
  })
}

const refresh = ref(false);
const isLoadBegin = ref(true);
const finishLoad = ref(false);
const isLoading = ref(false)

const userInfo = ref({
  username: 'test',
  description: '吾心吾行澄如明镜，所作所为皆是正义。吾心吾行澄如明镜，所作所为皆是正义。',
  level: 20,
  gender: '男',
  avatarImgUrl: '',
  userId: ''
});

const loadCard = () => {
  let a = {
    start: start.value,
    pageSize: pageSize
  };
  let data = qs.stringify(a);
  request.post(BASE_URL + '/v1/card/selectLimit', data).then((response) => {
    if (response.data.code === 2000) {
      list.value = response.data.data;
      isLoading.value = false;
      start.value += pageSize;
      cardList.value.push(...list.value)
    }
  }).finally(() => {
    isLoading.value = false
  })
}

const acceptInit = () => {
  loadOrder();
  loadAccepted();
}

const loadOrder = () => {
  request({
    method: "get",
    url: BASE_URL + '/v1/order/selectAll?orderStatus=待接单'
  }).then(res => {
    if (res.data.code === 2000) {
      orderList.value = res.data.data;
      orderImgSet(orderList);
    }
  })
}

const loadAccepted = () => {
  let a = {
    riderId: userInfo.value.userId,
    orderStatus: '进行中'
  }
  let data = qs.stringify(a);
  console.log(data)
  request({
    method: "post",
    url: BASE_URL + '/v1/rider/selectOrder',
    data: data
  }).then(res => {
    if (res.data.code === 2000) {
      acceptOrder.value = null;
      if (res.data.data.length !== 0) {
        acceptList.value = res.data.data;
        orderImgSet(acceptList)
        acceptOrder.value = acceptList.value[0];
        acceptOrder.value.creationTime = new Date(acceptOrder.value.creationTime);
      }
    }
  })
}

const recommendScroll = () => {
  refresh.value = true;
  console.log(list.value.length)
  if (list.value.length < 10) {
    isLoading.value = false;
    finishLoad.value = true;
    refresh.value = false;
  } else {
    isLoading.value = true;
    // 获取下一页的数据
    loadCard();
  }
}
const eventScroll = () => {

}

const acceptScroll = () => {

}

const orderList = ref([]);
const acceptList = ref([]);
const acceptOrder = ref(null)

const orderSquare = () => {
  request.get(BASE_URL + "/v1/order/selectAll?orderStatus=待接单").then((response) => {
    if (response.data.code === 2000) {
      orderList.value = response.data.data;
      orderImgSet(orderList);
    }
  })
}

const orderImgSet = (list) => {
  let len = list.value.length;
  for (let i = 0; i < len; i++) {
    if (list.value[i].orderType === '拿外卖') {
      list.value[i].orderImg = '/food.png';
    } else if (list.value[i].orderType === '打饭') {
      list.value[i].orderImg = '/hungry.png';
    } else if (list.value[i].orderType === '送厕纸') {
      list.value[i].orderImg = '/wc.png';
    } else if (list.value[i].orderType === '拿快递') {
      list.value[i].orderImg = '/express delivery.png';
    } else if (list.value[i].orderType === '跑腿') {
      list.value[i].orderImg = '/runleg.png';
    } else {
      list.value[i].orderImg = '/runleg.jpg';
    }
  }
}

const handleTabsChange = (name) => {
  showToast(name)
  switch (name) {
    case 'accept' :
      acceptInit();
      break;
  }
}

//简单策略模式，根据不同的页面选择不同的处理器
const handleScroll = (e, type) => {
  const scrollview = e.target;
  // 滚动条滚动时，距离顶部的距离
  const scrollTop = scrollview.scrollTop;
  // 可视区的高度
  const windowHeight = scrollview.clientHeight;
  // 滚动条的总高度
  const scrollHeight = scrollview.scrollHeight;
  // 当滚动条滚动到底部 并且 当前数据小于总数时进行翻页
  pullDisable.value = scrollTop !== 0;
  if (scrollTop + windowHeight + 10 >= scrollHeight && !isLoading.value) {
    switch (type) {
      case 'recommend' :
        recommendScroll();
        break;
      case 'event' :
        eventScroll();
        break;
      case 'accept' :
        acceptScroll();
        break;
    }
  }
}


const arriveOrder = () => {
  showLoadingToast({message:'定位中',duration: 0})

  //如果该对象存在，那么地理位置服务可用。
  if ('geolocation' in navigator) {
    /* 地理位置服务可用 */
    let options = {
      enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
      timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
      maximumAge: 0 //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
    }

    function success(position) {
      let lat = position.coords.latitude //当前位置的纬度
      let lng = position.coords.longitude //当前位置精度
      //todo 直接获取的经纬度还需要及逆行坐标转换校准
      let p = coordtransform.wgs84togcj02(lng, lat)
      p = coordtransform.gcj02tobd09(p[0], p[1])
      let info = {
        x: p[0],
        y: p[1],
        orderId: acceptOrder.value.orderId
      };
      let data = qs.stringify(info);
      request({
        method: "post",
        url: BASE_URL + '/v1/position/check',
        data: data
      }).then(res => {
        if (res.data.code === 2000) {
          console.log(res.data.data)
          let a = {
            orderId: acceptOrder.value.orderId,
            orderStatus: '待评价'
          }
          let data = qs.stringify(a);
          request({
            method: "post",
            url: BASE_URL + '/v1/order/insert',
            data: data
          }).then(res => {
            if (res.data.code === 2000) {
              showSuccessToast('成功送达')
              acceptDialog.value.show = false;

              setTimeout(() => {
                acceptInit()
              },500)
            }
          })
        }
      })
    }

    function error(err) {
      var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时']
      showFailToast(errorType[err.code - 1])
    }

    navigator.geolocation.getCurrentPosition(success, error, options)
  } else {
    /* 地理位置服务不可用 */
    console.log('无法获取您的位置，请检查定位是否开启或刷新重试')
  }
}

onMounted(() => {
  nextTick(() => {
    userInfo.value = currentUser.value
    userInfo.value.avatarImgUrl = BASE_URL + '/original' + currentUser.value.avatarImgUrl;
    switch (activeTab.value) {
      case 'recommend' :
        pullLoading();
        break;
      case 'accept' :
        acceptInit();
        break;
    }
  })
})

watch(activeTab,(newVal,oldVal) => {
  console.log(newVal,oldVal)
  nextTick(() => {
    handleTabsChange(newVal);
  })
})
</script>

<template>
  <div
      style="width: 100%;display: flex;justify-content: space-between;align-items: center;padding: 0 20px;box-sizing: border-box">
    <router-link to="/user" style="text-decoration: none">
      <van-image round fit="cover" v-model:src="userInfo.avatarImgUrl" width="40px" height="40px"/>
    </router-link>
    <router-link to="/search" style="text-decoration: none;width: 80%">
      <van-search/>
    </router-link>
    <router-link to="/message" style="text-decoration: none;color: black">
      <van-icon name="chat-o" size="25"/>
    </router-link>
  </div>
  <van-tabs v-model:active="activeTab" animated swipeable>
    <van-tab title="推荐" name="recommend" class="tab-background">
      <van-pull-refresh v-model="loading" @refresh="pullLoading" :disabled="pullDisable">
        <div class="ScrollBar"
             style="height: 80vh;padding: 0 10px;margin: 10px 0;overflow-y: scroll; display: flex;align-items: center;justify-content: center;flex-direction: column;box-sizing: border-box"
             @scroll="handleScroll($event,'recommend')">
          <div style="height: 100%;width: 100%;">
            <div style="display: grid;grid-gap: 5px;grid-auto-flow: row;grid-template-columns: repeat(2, 1fr);">
              <div v-for="item in cardList" style="height: 200px;border-radius: 3px;overflow: hidden;background-color:#fff;box-shadow: 0 1px 5px #a2a2a2">
                <van-skeleton title avatar :row="3" :loading="loading">
                  <div style="height: 120px">
                    <van-image :src="BASE_URL+'/compression'+(item.cardImgUrls[0]).slice(0,(item.cardImgUrls[0]).indexOf('.')) + '.jpg'" height="100%" width="100%" fit="cover"/>
                  </div>
                  <div style="height: 70px;display: flex;padding: 5px;flex-direction: column;justify-content: space-between;gap: 5px;">
                    <van-text-ellipsis :content="item.title" rows="2" style="font-size: 14px"/>
                    <div style="display: flex;align-items: center;gap: 5px">
                      <van-image round :src="BASE_URL+'/compression'+(item.avatarImgUrl).slice(0,(item.cardImgUrls[0]).indexOf('.')) + '.jpg'" width="20px" height="20px"/>
                      <span style="font-size: 10px;color: #a2a2a2">{{ item.nickname }}</span>
                    </div>
                  </div>
                </van-skeleton>
              </div>
            </div>
            <div style="width: 100%;height: 60px;display: flex;align-items: center;justify-content: center">
              <van-loading vertical v-show="isLoading">
                <template #icon>
                  <van-icon name="star-o" size="30"/>
                </template>
                加载中...
              </van-loading>
              <div v-show="finishLoad" style="font-size: 15px;color: #56d27f; display: flex;justify-content: center;align-items: center;margin: 5px 0">
                已经到底咯~
              </div>
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </van-tab>
    <van-tab title="活动" name="event" class="tab-background">
      <div class="ScrollBar"
           style="height: 80vh;padding: 0 10px;margin: 10px 0;overflow-y: scroll; display: flex;align-items: center;justify-content: center;flex-direction: column;box-sizing: border-box"
           @scroll="handleScroll($event,'event')">
        <div style="height: 100%;width: 100%;">
          <div style="display: flex;align-items: center;justify-content: center;flex-direction: column;gap: 10px">
            <div style="width: 100%;border-radius: 3px;overflow-y: scroll;background-color:#fff;box-shadow: 0 1px 5px #a2a2a2" v-for="item in 40">
              <div style="width: 100%;height: 100px;">
                <van-image fit="cover" width="100%" height="100%"/>
              </div>
              <div style="display: flex;align-items: center;justify-content: space-between;margin: 5px">
                <span>这是一个精彩活动</span>
                <div>
                  <van-icon name="fire-o" color="#ee0a24" />
                  114514
                </div>
              </div>
            </div>
          </div>
          <div style="width: 100%;height: 60px;display: flex;align-items: center;justify-content: center">
            <van-loading vertical v-show="isLoading">
              <template #icon>
                <van-icon name="star-o" size="30"/>
              </template>
              加载中...
            </van-loading>
            <div v-show="finishLoad" style="font-size: 15px;color: #56d27f; display: flex;justify-content: center;align-items: center;margin: 5px 0">
              已经到底咯~
            </div>
          </div>
        </div>
      </div>
    </van-tab>
    <van-tab title="接单" name="accept" class="tab-background" v-if="userInfo.level === 20">
      <div
          style="height: 80vh;padding: 0 10px;margin: 10px 0;overflow-y: scroll; display: flex;align-items: center;justify-content: center;flex-direction: column;box-sizing: border-box"
          @scroll="handleScroll($event,'accept')"
      >
        <div style="width: 100%;height: 100%;">
          <div style="width: 100%;box-shadow: 0 1px 5px #a2a2a2;padding: 5px;margin-bottom: 10px;box-sizing: border-box;border-radius: 3px"  v-if="acceptOrder !== null">
            <div>
              <span style="font-size: 15px">派送中</span>
            </div>
            <div style="display: flex;align-items: center;justify-content: space-between;" @click="acceptDialog.show = true">
              <van-card
                  :price="acceptOrder.orderPrice"
                  :title="acceptOrder.orderTitle"
                  :thumb="acceptOrder.orderImg"
                  style="width: 70%;"
              >
                <template #desc>
                  <van-text-ellipsis :content="acceptOrder.orderDescription" rows="2"/>
                </template>
                <template #tags>
                  <div style="display: flex;align-items: center;justify-content: left;gap: 5px">
                    <van-tag plain type="success">{{acceptOrder.orderType}}</van-tag>
                    <van-tag plain type="success">{{acceptOrder.endLocation}}</van-tag>
                  </div>
                </template>
              </van-card>
              <div style="display: flex;align-items: center;justify-content: center;flex-direction: column">
                <span style="color: #e61616">剩余时间</span>
                <van-count-down :time="acceptOrder.creationTime.getTime()+1800000-new Date().getTime()">
                  <template #default="timeData">
                    <span class="block">{{ timeData.hours }}</span>
                    <span class="colon">:</span>
                    <span class="block">{{ timeData.minutes }}</span>
                    <span class="colon">:</span>
                    <span class="block">{{ timeData.seconds }}</span>
                  </template>
                </van-count-down>
              </div>
            </div>
          </div>
          <van-divider style="margin: 10px 0">待接订单</van-divider>
          <div style="display: flex;align-items: center;justify-content: center;flex-direction: column;gap: 10px;padding-top: 5px">
            <router-link v-for="num in orderList" :to="'/reception?orderId='+num.orderId" style="background-color:#fff;box-shadow: 0 1px 5px #a2a2a2;width: 100%;">
              <van-card
                  :price="num.orderPrice"
                  :desc="num.orderDescription"
                  :title="num.orderTitle"
                  :thumb="num.orderImg"
              >
                <template #tags>
                  <div style="display: flex;align-items: center;justify-content: left;gap: 5px">
                    <van-tag plain type="success">{{num.orderType}}</van-tag>
                    <van-tag plain type="success">{{num.endLocation}}</van-tag>
                  </div>
                </template>
                <template #footer>
                  <van-button type="success" size="small">接单</van-button>
                </template>
              </van-card>
            </router-link>
          </div>
          <div style="width: 100%;height: 60px;display: flex;align-items: center;justify-content: center">
            <van-loading vertical v-show="isLoading">
              <template #icon>
                <van-icon name="star-o" size="30"/>
              </template>
              加载中...
            </van-loading>
            <div v-show="finishLoad" style="font-size: 15px;color: #56d27f; display: flex;justify-content: center;align-items: center;margin: 5px 0">
              已经到底咯~
            </div>
          </div>
        </div>
      </div>
    </van-tab>
    <van-tab title="更多" name="more" class="tab-background">
      <div style="display: flex;align-items: center;justify-content: center;height: 80vh;padding: 0 10px;margin: 10px 0;box-sizing: border-box">
        <van-empty
            image-size="80"
            description="敬请期待"
        />
      </div>
    </van-tab>
  </van-tabs>

  <van-dialog v-if="acceptOrder" v-model:show="acceptDialog.show" title="订单详情" :showConfirmButton="false" :closeOnClickOverlay="true">
    <div style="display: flex;align-items: center;justify-content: left;flex-direction: column;width: 100%;padding: 30px;box-sizing: border-box;gap: 30px">
      <div style="display: flex;align-items: center;justify-content: left;flex-direction: column;width: 100%;gap: 10px">
        <div style="display: flex;align-items: center;justify-content: left;width: 100%;gap: 30px">
          <span style="width: 30%;">订单标题:</span>
          <span style="width: 55%;">{{acceptOrder.orderTitle}}</span>
        </div>
        <div style="display: flex;align-items: center;justify-content: left;width: 100%;gap: 30px">
          <span style="width: 30%;">订单描述:</span>
          <van-text-ellipsis style="width: 55%;" :content="acceptOrder.orderDescription" rows="3"/>
        </div>
        <div style="display: flex;align-items: center;justify-content: left;width: 100%;gap: 30px">
          <span style="width: 30%;">订单价格:</span>
          <span style="width: 55%;">￥{{acceptOrder.orderPrice}}</span>
        </div>
        <div style="display: flex;align-items: center;justify-content: left;width: 100%;gap: 30px">
          <span style="width: 30%;">目的地:</span>
          <span style="width: 55%;">{{acceptOrder.endLocation}}</span>
        </div>
        <div style="display: flex;align-items: center;justify-content: left;width: 100%;gap: 30px">
          <span style="width: 30%;">详细地址:</span>
          <van-text-ellipsis style="width: 55%;" :content="acceptOrder.detailedEndLocation" rows="3"/>
        </div>
      </div>
      <div style="width: 100%;">
        <van-button type="success" round style="width: 100%" @click="arriveOrder">确认送达</van-button>
      </div>
    </div>
  </van-dialog>
</template>

<style scoped>
.tab-background {
  background-color: #fafafa
}

.colon {
  display: inline-block;
  margin: 0 4px;
  color: #1989fa;
}
.block {
  display: inline-block;
  width: 22px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background-color: #1989fa;
}
</style>